//package com.example.demo.multidatasource;
//
//import org.apache.log4j.Logger;
//import org.hibernate.internal.SessionFactoryImpl;
//import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
//import org.springframework.orm.hibernate5.SessionFactoryUtils;
//
//import javax.sql.DataSource;
//import java.io.PrintWriter;
//import java.sql.Connection;
//import java.sql.SQLException;
//import java.sql.SQLFeatureNotSupportedException;
//import java.util.HashMap;
//import java.util.Map;
//import java.util.Set;
//import java.util.concurrent.locks.ReentrantLock;
//
///**
// * @author Jack
// * @Title: 动态数据源
// * @Description: 动态数据源
// * @date 2018年1月7日14:31:12
// */
//public class MultiDataSource implements DataSource {
//    // 默认的数据源类型
//    private static final String DEFAULT_DATASOUCE_TYPE = "com.alibaba.druid.pool.DruidDataSource";
//    private final ReentrantLock lock = new ReentrantLock();
//    private Logger logger = Logger.getLogger(MultiDataSource.class);
//    private static Map<Long, DataSource> dsMap;
//    private static MultiDataSource multiDataSource = new MultiDataSource();
//
//    private MultiDataSource() {
//        dsMap = new HashMap<Long, DataSource>();
//    }
//
//    public static MultiDataSource getInstance() {
//        return multiDataSource;
//    }
//
//    public DataSource getDataSource() {
//        Long dataSourceKey = this.getDataSourceKey();
//        this.logger.info("Get Data Source...");
//        DataSource dataSource = dsMap.get(dataSourceKey);
//        if (null != dataSource) {
//            return dataSource;
//        }
//        dataSource = this.newDataSource();
//        if (null != dataSource) {
//            return dataSource;
//        }
//        throw new RuntimeException("获取数据源失败");
//    }
//
//    private DataSource newDataSource() {
//        this.logger.info("Build Data Source...");
//        Long dataSourceKey = this.getDataSourceKey();
//        // 根据HTTP接口获取数据源配置信息
//        Map<String, Object> dataSourceMap = this.getDataSourceConfigure();
//        DataSource dataSource = this.buildDataSource(dataSourceMap);
//        if (null != dataSourceKey && null != dataSource) {
//            dsMap.put(dataSourceKey, dataSource);
//            return dataSource;
//        }
//        if (null != dataSource) {
//            return dataSource;
//        }
//        throw new RuntimeException("新建数据源失败");
//    }
//
//    private DataSource buildDataSource(Map<String, Object> dataSourceMap) {
//        Object type = dataSourceMap.get("type");
//        type = type == null ? DEFAULT_DATASOUCE_TYPE : type;
//        try {
//            Class<? extends DataSource> dataSourceType = (Class<? extends DataSource>) Class
//                    .forName(type.toString());
//            String driverClassName = dataSourceMap.get("driver-class-name").toString();
//            String url = dataSourceMap.get("url").toString();
//            String username = dataSourceMap.get("username").toString();
//            String password = dataSourceMap.get("password").toString();
//            return DataSourceBuilder.create().type(dataSourceType).driverClassName
//                    (driverClassName).url(url)
//                    .username(username).password(password).build();
//        } catch (ClassNotFoundException e) {
//            logger.error("创建数据源失败：{}", e);
//            return null;
//        }
//    }
//
//    private Map<String, Object> getDataSourceConfigure() {
//        Long dataSourceKey = this.getDataSourceKey();
//        Map<String, Object> configureMap = new HashMap<>();
//        if (dataSourceKey == null) {
//            configureMap.put("url", "jdbc:postgresql://192.168.0.202:25432/boottest");
//            configureMap.put("username", "postgres");
//            configureMap.put("password", "emintest");
//            configureMap.put("driver-class-name", "org.postgresql.Driver");
//        } else {
//            if (dataSourceKey.compareTo(new Long(1L)) == 0) {
//                configureMap.put("url", "jdbc:postgresql://192.168.0.202:25432/boottest");
//                configureMap.put("username", "postgres");
//                configureMap.put("password", "emintest");
//                configureMap.put("driver-class-name", "org.postgresql.Driver");
//            } else {
//                configureMap.put("url", "jdbc:postgresql://localhost:5432/test");
//                configureMap.put("username", "postgres");
//                configureMap.put("password", "123456");
//                configureMap.put("driver-class-name", "org.postgresql.Driver");
//            }
//
//        }
//        return configureMap;
//    }
//
//    private Connection getCurrentEminConnection() {
//        this.lock.tryLock();
//        try {
//            DataSource ds = this.getDataSource();
//            Connection conn = ds.getConnection();
//            System.out.println("Conn in Company:" + conn.getMetaData().getURL());
//            Connection connection = conn;
//            return connection;
//        } catch (Exception var7) {
//            this.logger.info("Get connection failed:" + var7.getMessage());
//            var7.printStackTrace();
//        } finally {
//            if (this.lock.isHeldByCurrentThread()) {
//                this.lock.unlock();
//            }
//
//        }
//        return null;
//    }
//
//    public Boolean containDataSourceKey(Long dataSourceKey) {
//        return dsMap.containsKey(dataSourceKey);
//    }
//
//    private Long getDataSourceKey() {
//        return DynamicDataSourceContextHolder.getDataSourceKey();
//    }
//
//    public Set<Map.Entry<Long, DataSource>> getDataSourceSet() {
//        return dsMap.entrySet();
//    }
//
//    public void putDataSource(Long currentDataSourceKey, DataSource currentDataSource) {
//        dsMap.put(currentDataSourceKey, currentDataSource);
//    }
//
//    public void removeDataSource(Long dataSourceKey) {
//        dsMap.remove(dataSourceKey);
//    }
//
//
//    @Override
//    public Connection getConnection() throws SQLException {
//        return this.getCurrentEminConnection();
//    }
//
//    @Override
//    public Connection getConnection(String username, String password) throws SQLException {
//        return this.getDataSource().getConnection();
//    }
//
//    @Override
//    public <T> T unwrap(Class<T> iface) throws SQLException {
//        return this.getDataSource().unwrap(iface);
//    }
//
//    @Override
//    public boolean isWrapperFor(Class<?> iface) throws SQLException {
//        return this.getDataSource().isWrapperFor(iface);
//    }
//
//    @Override
//    public PrintWriter getLogWriter() throws SQLException {
//        return this.getDataSource().getLogWriter();
//    }
//
//    @Override
//    public void setLogWriter(PrintWriter out) throws SQLException {
//        this.getDataSource().setLogWriter(out);
//    }
//
//    @Override
//    public void setLoginTimeout(int seconds) throws SQLException {
//        this.getDataSource().setLoginTimeout(seconds);
//    }
//
//    @Override
//    public int getLoginTimeout() throws SQLException {
//        return this.getDataSource().getLoginTimeout();
//    }
//
//    @Override
//    public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
//        return this.getDataSource().getParentLogger();
//    }
//
//
//    public DataSource getLocalDataSourceByConnectionProvider(SessionFactoryImpl sessionFactory) {
//        return SessionFactoryUtils.getDataSource(sessionFactory);
//    }
//}
